package com.voicechat.firstmet.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PayResult;
import com.voicechat.firstmet.bean.ShareGirlsDetailsBean;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.AlipaySerivice;
import com.voicechat.firstmet.net.service.FaintService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity
 * @ClassName: BlindDateDemandActivity
 * @Description: 相亲需求页面
 * @Author: ljp
 * @CreateDate: 2019/1/17 15:09
 * @Version: 1.0
 */
public class BlindDateDemandActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.et_blind_data_address)
    TextView etBlindDataAddress;
    @BindView(R.id.et_blind_data_time)
    EditText etBlindDataTime;
    @BindView(R.id.et_blind_data_way)
    EditText etBlindDataWay;
    @BindView(R.id.et_blind_data_remarks)
    TextView etBlindDataRemarks;
    @BindView(R.id.tv_open_vip)
    TextView tvOpenVip;
    @BindView(R.id.rela_vip)
    RelativeLayout relaVip;
    @BindView(R.id.tv_share_red)
    TextView tvShareRed;
    @BindView(R.id.tv_vip_parse)
    TextView tvVipParse;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String deviceInfo;
    private String TAG = "BlindDateDemandActivity";
    private String price;
    private String id;
    private String token;
    private int engTime;//约会时间，时间 3(3天内) 5(5天内) 7(7天内)
    private int engWay;//陪同标记 1陪同 2不陪同
    private static final int SDK_PAY_FLAG = 1;
    private int pariceReal;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        try {
                            JSONObject jsonObject = new JSONObject(resultInfo);
                            if (jsonObject.has("alipay_trade_app_pay_response")) {
                                JSONObject alipay_trade_app_pay_response = jsonObject.getJSONObject("alipay_trade_app_pay_response");
                                if (alipay_trade_app_pay_response.has("out_trade_no")) {
                                    String out_trade_no = alipay_trade_app_pay_response.getString("out_trade_no");
                                    judeRecharge(out_trade_no);//判断是否购买成功
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        tvPay.setEnabled(true);
                        toast_MakeText("支付已经取消");
                    } else {
                        tvPay.setEnabled(true);
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //showPopu();//弹出购买失败框
                    }
                    break;
                }
            }
        }
    };
    /**
     * @return
     * @method
     * @description 购买结果的判断
     * @date: 2019/1/10 10:09
     * @author: ljp
     */
    private void judeRecharge(String orderStr) {
        AlipaySerivice.judeAlipay(orderStr).subscribe(result -> {
            tvPay.setEnabled(true);
            Log.i(TAG, "judeRecharge: -----" + result.toString());
           /* if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                Intent intent = new Intent(activity, AllSuccessActivity.class);
                intent.putExtra("flag", "2");
                startActivity(intent);
                finish();
            } else {*/
                toast_MakeText(result.getMsg());
               // showPopu();//弹出购买失败框
            //}
        }, throwable -> {
            tvPay.setEnabled(true);
            toast_MakeText(getResources().getString(R.string.net_error));
           // showPopu();//弹出购买失败框
            Log.i(TAG, "judeRecharge: ---------" + throwable.toString());
        });
    }

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_blind_data;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        id = getIntent().getStringExtra("id");//闺蜜信息id
        price = getIntent().getStringExtra("Price");
        initView();
    }

    private void initView() {
        pariceReal = Integer.parseInt(price);
        if (mySeleInfo.getvType().equals("0")) {// 会员类型  0非会员 1月会员 2年会员
            relaVip.setVisibility(View.VISIBLE);
        } else {
            relaVip.setVisibility(View.GONE);
        }
        tvShareRed.setText("￥" + price);
        int i = (int) Math.ceil(Integer.parseInt(price) * 0.8);
        tvVipParse.setText("会员价：￥" + i);
    }

    @OnClick({R.id.linear_back, R.id.et_blind_data_address,
            R.id.et_blind_data_time, R.id.et_blind_data_way,
            R.id.et_blind_data_remarks, R.id.tv_open_vip,
            R.id.rela_vip, R.id.tv_pay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back://返回
                finish();
                break;
            case R.id.et_blind_data_address:
                Intent intent  = new Intent(activity, BlindDateDemandRemarksActivity.class);
                intent.putExtra("flag","2");
                intent.putExtra("number",100);
                if(!TextUtils.isEmpty(etBlindDataAddress.getText().toString().trim()) ){
                    intent.putExtra("address",etBlindDataAddress.getText().toString().trim());
                }
                startActivityForResult(intent,100);
                break;
            case R.id.et_blind_data_time://选择见面时间
                showPopuTime();
                break;
            case R.id.et_blind_data_way://选择见面方式
                showPopuWay();
                break;
            case R.id.et_blind_data_remarks://输入备注
                Intent intent2  = new Intent(activity, BlindDateDemandRemarksActivity.class);
                intent2.putExtra("number",140);
                intent2.putExtra("flag","1");
                if(!TextUtils.isEmpty(etBlindDataRemarks.getText().toString().trim()) ){
                    intent2.putExtra("remark",etBlindDataRemarks.getText().toString().trim());
                }
                startActivityForResult(intent2,100);
                break;
            case R.id.tv_open_vip://开通会员
                break;
            case R.id.rela_vip:
                break;
            case R.id.tv_pay://去支付
                //judeRecharge("MD_15481429148341");
                setOrder();
                break;
        }
    }
    /**
    * @method
    * @description 获取订单信息
    * @date: 2019/1/21 17:13
    * @author: ljp
    * @return
    */
    private void setOrder() {
        String address = etBlindDataAddress.getText().toString().trim();
        String remarks = null;
        if(TextUtils.isEmpty(address)){
            toast_MakeText("请输入约会地点");
            return;
        }
        if(engTime == 0){
            toast_MakeText("请选择约会时间");
            return;
        }
        if(engWay == 0){
            toast_MakeText("请选择约会方式");
            return;
        }
        if(!TextUtils.isEmpty(etBlindDataRemarks.getText().toString().trim())){
            remarks = etBlindDataRemarks.getText().toString().trim();
        }
        tvPay.setEnabled(false);
        FaintService.shareGirlsOrder(token,deviceInfo,id,mySeleInfo.getId(),
                address,engTime,engWay,remarks).subscribe(shareGirlsDetailsBean -> {
                    if(shareGirlsDetailsBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                        //直接支付宝支付，先去请求订单
                        getPayOrder(shareGirlsDetailsBean.getObject());
                    }else if (shareGirlsDetailsBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        Utils.setToken(context);
                    } else {
                        toast_MakeText(shareGirlsDetailsBean.getMsg());
                    }
        },throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK) {
            if (requestCode == 100) {
                String flag = data.getStringExtra("flag");
                if(flag.equals("1")){
                    String remarks = data.getStringExtra("remark");
                    etBlindDataRemarks.setText(remarks);
                }else {
                    String address = data.getStringExtra("address");
                    etBlindDataAddress.setText(address);
                }

            }
        }
    }
    LinearLayout linear3Day;
    LinearLayout linear5Day;
    LinearLayout linear7Day;
    TextView tv3Day;
    TextView tv5Day;
    TextView tv7Day;
    CheckBox cb3Day;
    CheckBox cb5Day;
    CheckBox cb7Day;
    LinearLayout linearNoGirls;
    LinearLayout linearHaveGirls;
    TextView tvNoGirls;
    TextView tvHaveGirls;
    CheckBox cbNoGirls;
    CheckBox cbHaveGirls;
    String time;
    String way;
    //选择见面时间
    private void showPopuTime() {
        View view = View.inflate(context, R.layout.popu_blind_data, null);
        linear3Day = view.findViewById(R.id.linear_3);
        linear5Day = view.findViewById(R.id.linear_5);
        linear7Day = view.findViewById(R.id.linear_7);
        tv3Day = view.findViewById(R.id.tv_3);
        tv5Day = view.findViewById(R.id.tv_5);
        tv7Day = view.findViewById(R.id.tv_7);
        cb3Day = view.findViewById(R.id.radio_3_day);
        cb5Day = view.findViewById(R.id.radio_5_day);
        cb7Day = view.findViewById(R.id.radio_7_day);
        TextView tvSure = view.findViewById(R.id.tv_sure);
        linear3Day.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                engTime = 3;
                clearTime();
                selectTime(tv3Day,cb3Day);
            }
        });
        linear5Day.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                engTime = 5;
                clearTime();
                selectTime(tv5Day,cb5Day);
            }
        });
        linear7Day.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                engTime = 7;
                clearTime();
                selectTime(tv7Day,cb7Day);
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               etBlindDataTime.setText(time);
                PopUtils.hidePopupWindow();
            }
        });
        PopUtils.initPopupWindow(activity, view, false);
    }
    //选择见面方式
    private void showPopuWay() {
        View view = View.inflate(context, R.layout.popu_blind_data_way, null);
        linearNoGirls = view.findViewById(R.id.linear_no_girls);
        linearHaveGirls = view.findViewById(R.id.linear_have_girls);
        tvHaveGirls = view.findViewById(R.id.tv_have_girls);
        tvNoGirls = view.findViewById(R.id.tv_no_girls);
        cbNoGirls = view.findViewById(R.id.radio_no_girls);
        cbHaveGirls = view.findViewById(R.id.radio_have_girls);
        TextView tvSure = view.findViewById(R.id.tv_sure);
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etBlindDataWay.setText(way);
                PopUtils.hidePopupWindow();
            }
        });
        linearNoGirls.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                engWay = 2;
                clearway();
                selectWay(tvNoGirls,cbNoGirls);
            }
        });
        linearHaveGirls.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                engWay = 1;
                clearway();
                selectWay(tvHaveGirls,cbHaveGirls);
            }
        });
        PopUtils.initPopupWindow(activity, view, false);
    }
    /**
    * @method
    * @description 清除选定时间
    * @date: 2019/1/18 17:17
    * @author: ljp
    * @return
    */
    private void clearTime(){
        tv3Day.setTextColor(getResources().getColor(R.color.colorAAAAAA));
        cb3Day.setChecked(false);
        tv5Day.setTextColor(getResources().getColor(R.color.colorAAAAAA));
        cb5Day.setChecked(false);
        tv7Day.setTextColor(getResources().getColor(R.color.colorAAAAAA));
        cb7Day.setChecked(false);
    }
    /**
    * @method
    * @description 清除选定方式
    * @date: 2019/1/18 17:17
    * @author: ljp
    * @return
    */
    private void clearway(){
        tvNoGirls.setTextColor(getResources().getColor(R.color.colorAAAAAA));
        cbNoGirls.setChecked(false);
        tvHaveGirls.setTextColor(getResources().getColor(R.color.colorAAAAAA));
        cbHaveGirls.setChecked(false);
    }
    /**
    * @method
    * @description 选定时间
    * @date: 2019/1/18 17:19
    * @author: ljp
    * @return
    */
    private void selectTime(TextView textView,CheckBox cb){
        time = textView.getText().toString().trim();
        textView.setTextColor(getResources().getColor(R.color.colorFFC301));
        cb.setChecked(true);
    }
    /**
     * @method
     * @description 选定方式
     * @date: 2019/1/18 17:19
     * @author: ljp
     * @return
     */
    private void selectWay(TextView textView,CheckBox cb){
        way = textView.getText().toString().trim();
        textView.setTextColor(getResources().getColor(R.color.colorFFC301));
        cb.setChecked(true);
    }
    /**
    * @method
    * @description 请求订单号
    * @date: 2019/1/21 17:48
    * @author: ljp
    * @return
    */
    public void getPayOrder(ShareGirlsDetailsBean.ObjectBean objectBean) {
        AlipaySerivice.getShareGirlsOrder(objectBean.getFriendReleaseId(),objectBean.getId(),objectBean.getUserId(),
                objectBean.getAddress(),objectBean.getTime(),objectBean.getAccompany(),objectBean.getRemarks(),
                objectBean.getReceiptStatus(),objectBean.getComplete(),objectBean.getCancelSign(),pariceReal).subscribe(alipayBean -> {
            if(alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                Log.i(TAG, "getPayOrder: -----getOrderName----"+alipayBean.getMap().getOrderName());
                //judeRecharge(alipayBean.getMap().getOrderName());
                setAlipay(alipayBean.getMap().getOrderStr());
            }else if(alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN){
                Utils.setToken(context);
            }else {
                toast_MakeText(alipayBean.getMsg());
            }
        },throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "toPay: ---------"+throwable.toString());
        });
    }
    /**
     * @return
     * @method
     * @description 支付宝支付
     * @date: 2019/1/10 10:44
     * @author: ljp
     */
    private void setAlipay(String orderInfo) {
        Log.i(TAG, "setAlipay: -------orderInfo-----"+orderInfo);
        final Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i(TAG, "run: -----------" + result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
